package src.ee.ioc.smaug.world.evolution;

import java.util.Random;
import src.ee.ioc.smaug.world.beings.Individual;
import src.ee.ioc.smaug.world.evolution.Evolution;

public class Selection {

    public static void apply() {

        switch (EnvDescription.SELtype) {
        case ROULETTE_WHEEL_SELECTION:
            rouletteWheelSelection();
            break;
        }

    }

    public static void rouletteWheelSelection() {
        int sumFitness = 0;
        for (int i = 0; i < Evolution.population.size(); i++) {
            Individual being = Evolution.population.get(i);
            sumFitness += being.getFitness();
        }
        for (int i = 0; i < Evolution.population.size(); i++) {
            Individual being = Evolution.population.get(i);
            int likelihood = (int) Math
                    .round((being.getFitness() / sumFitness) * 100);
            being.probabilityOfBeingSelected = likelihood;
        }
    }

    private static int searchInd(int probability) {
        int number = 0;
        int cum = 0;
        for (int i = 0; i < Evolution.population.size(); i++) {
            Individual being = Evolution.population.get(i);
            cum += being.probabilityOfBeingSelected;

            if (cum >= probability) {
                number = i;
                break;
            }

        }
        return number;
    }

    public static Individual getIndividualForBreeding() {
        Random rnd = new Random();
        return Evolution.population.get(searchInd(rnd.nextInt(101)));
    }

}
